package org.jeecg.modules.gis.typeHandler.postgis;


import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.ParseException;
import org.locationtech.jts.io.WKBReader;
import org.locationtech.jts.io.WKBWriter;


import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Geometry字段和MyBatis类型转换器
 *
 * @param <T> 具体的几何类型
 * @author wangrubin
 * @date 2022-08-06
 */
public abstract class AbstractGeometryTypeHandler<T extends Geometry> extends BaseTypeHandler<T> {

    private static final WKBWriter WKB_WRITER = new WKBWriter();

    private static final WKBReader WKB_READER = new WKBReader();

    private static final ReentrantLock WRITE_LOCK = new ReentrantLock();

    private static final ReentrantLock READ_LOCK = new ReentrantLock();

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Geometry geometry, JdbcType jdbcType)
            throws SQLException {
        WRITE_LOCK.lock();
        //PostGIS 矢量数据存储方式为WKB
        byte[] write = WKB_WRITER.write(geometry);
        WRITE_LOCK.unlock();
        try (InputStream is = new ByteArrayInputStream(write)) {
            ps.setBinaryStream(i, is);
        } catch (IOException e) {
            throw new SQLException(e);
        }

    }

    @Override
    public T getNullableResult(ResultSet rs, String s) throws SQLException {
        return getGeometry(rs.getString(s));
    }

    @Override
    public T getNullableResult(ResultSet rs, int i) throws SQLException {
        return getGeometry(rs.getString(i));
    }

    @Override
    public T getNullableResult(CallableStatement cs, int i) throws SQLException {
        return getGeometry(cs.getString(i));
    }

    private T getGeometry(String wkbString) throws SQLException {
        if (StringUtils.isBlank(wkbString)) {
            return null;
        }
        byte[] bytes = WKBReader.hexToBytes(wkbString);
        READ_LOCK.lock();
        try {
            return (T)WKB_READER.read(bytes);
        } catch (ParseException e) {
            throw new SQLException(e);
        } finally {
            READ_LOCK.unlock();
        }
    }

}